﻿using log4net.Core;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using wnet.admin.CommQueue;

namespace wnet.admin.Comm
{
    public class AlarmData
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Data">二维数组 row * col 10 * 500</param>
        /// <param name="Row">行 10</param>
        /// <param name="Col">500</param>
        /// <param name="StartPoint">起始位置 point x</param>
        /// <param name="index"></param>
        /// <param name="bitmap"></param>
        /// <param name="Number"></param>
        /// <returns></returns>
        //钢丝绳缺陷特征
        public static string WireRrope_MagneticFluxLeakageCharacteristics(double[,] Data, int Row, int Col, int StartPoint)
        {
            int i;
            int j;
            int stu = 0;
            //获取相对变化值
            double[,] All_Temp = new double[Row, Col];
            for (i = 0; i < Row; i++)
            {
                double RowMeanValue = RowMeanVolue__2DDoubleCalculate(Data, i, Col);
                for (j = 0; j < Col; j++)
                {
                    All_Temp[i, j] = Data[i, j] - RowMeanValue;
                }
            }
            //整个缺陷区域最大值及其所在位置
            double[] MaxValue = new double[Row];
            double[] MinValue = new double[Row];
            double[] RowTemp = new double[Col];
            double MaxPPValue = 0;
            int MaxPPIndex = 0;
            for (i = 0; i < Row; i++)
            {
                for (j = 0; j < Col; j++)
                {
                    RowTemp[j] = All_Temp[i, j];
                }
                MaxValue[i] = MaxValue_1DDoubleCalculate(RowTemp, Col);
                MinValue[i] = MinValue_1DDoubleCalculate(RowTemp, Col);
            }
            double[] RowPPValue = new double[Row];
            for (i = 0; i < Row; i++)
            {
                RowPPValue[i] = MaxValue[i] - MinValue[i];
            }
            MaxPPValue = MaxValue_1DDoubleCalculate(RowPPValue, Row);
            MaxPPIndex = MaxIndex__1DDoubleCalculate(RowPPValue, Row);

            double Flux = 0;
            double Area = 0;
            for (i = 0; i < Row; i++)
            {
                for (j = 0; j < Col; j++)
                {
                    if (Math.Abs(Data[i, j]) > (MaxPPValue / 4))
                    {
                        //磁通量
                        Flux = Flux + Math.Abs(Data[i, j]);
                        //磁通面积
                        Area++;
                    }
                }
            }

            //switch (index)
            //{
            //    case 0:
            //        stu = 20;
            //        break;
            //    case 1:
            //        stu = 90;
            //        break;
            //    case 2:
            //        stu = 150;
            //        break;
            //    case 3:
            //        stu = 200;
            //        break;
            //}

            // MaxPPIndex 传感器编号  StartPoint 位置  //磁通量 Flux  面积 Area
            string Rcv = "最大峰峰值:" + MaxPPValue.ToString() + "最大峰峰值所在行:" + MaxPPIndex.ToString() + "所在位置:" + StartPoint.ToString() + "磁通量变化:" + Flux.ToString() + "磁通量面积:" + Area.ToString();
            //m 10 20 30 
            //探伤列表非持久化数据 序号 一次递增  报警内容：传感器编号 + 位置 （3# + 1000m（MaxPPIndex + StartPoint） ）  等级 1 2 3 时间
            //10 / 12小时
            double[] BrokenWire_AreaValue = new double[3] { 0, 0, 0};
            double[] BrokenWire_ThresholdValue = new double[3] { 0, 0, 0 };
            double[] BrokenWire_FluxValue = new double[3] { 3000, 3100, 3200 };
            if (Area >= BrokenWire_AreaValue[2] && MaxPPValue >= BrokenWire_ThresholdValue[2] && Flux >= BrokenWire_FluxValue[2])
            {
                addalarm(StartPoint, MaxPPIndex, "等级3", Area);
            }
            else if (Area >= BrokenWire_AreaValue[1] && MaxPPValue >= BrokenWire_ThresholdValue[1] && Flux >= BrokenWire_FluxValue[1])
            {
                addalarm(StartPoint, MaxPPIndex, "等级2", Area);
            }
            else if (Area >= BrokenWire_AreaValue[0] && MaxPPValue >= BrokenWire_ThresholdValue[0] && Flux >= BrokenWire_FluxValue[0])
            {
                addalarm(StartPoint, MaxPPIndex, "等级1", Area);
            }
            return Rcv;
        }

        private static void addalarm(int StartPoint, int MaxPPIndex,string AlarmLevel, double Area)
        {
            AlarmView alarmView = new AlarmView();
            alarmView.AlarmNo = AlarmNo++;
            alarmView.AlarmContent = $"{MaxPPIndex}";
            alarmView.Alarmlocation = $"{StartPoint}";
            alarmView.AlarmLevel = AlarmLevel;
            alarmView.Area = Area;

            alarmView.AlarmTime = DateTime.Now.ToString("HH:mm");
            // 检查 mAlarmViews 的大小是否已经达到10
            if (ConstDefine.mAlarmViews.Count >= 8)
            {
                // 如果集合大小达到或超过10，则移除第一个元素
                ConstDefine.mAlarmViews.RemoveAt(0);
            }
            ConstDefine.mAlarmViews.Add(alarmView);
            alarmView.alarmdate = DateTime.Now;

            WConstDefine.AddAlarmView(alarmView);
        }

        static int AlarmNo = 1;

        [DllImport("kernel32.dll")]
        public static extern bool Beep(int freq, int duration);
        //计算一维Double数组最大值
        public static double MaxValue_1DDoubleCalculate(double[] Data, int Length)
        {
            int i;
            double MaxValue = 0;
            for (i = 0; i < Length; i++)
            {
                if (Data[i] > MaxValue)
                {
                    MaxValue = Data[i];
                }
            }
            return MaxValue;
        }
        //计算一维Double数组最小值
        public static double MinValue_1DDoubleCalculate(double[] Data, int Length)
        {
            int i;
            double MinValue = 65535;
            for (i = 0; i < Length; i++)
            {
                if (Data[i] < MinValue)
                {
                    MinValue = Data[i];
                }
            }
            return MinValue;
        }
        //计算一维Int数组最大值及其序列号
        public static int MaxIndex_1DIntCalculate(int[] Data, int Length)
        {
            int i;
            int Temp = 0;
            int MaxIndex = 0;
            for (i = 0; i < Length; i++)
            {
                if (Math.Abs(Data[i]) > Temp)
                {
                    Temp = Math.Abs(Data[i]);
                    MaxIndex = i;
                }
            }
            return MaxIndex;
        }
        public static int MaxIndex__1DDoubleCalculate(double[] Data, int Length)
        {
            int i;
            double MaxValue = 0;
            int MaxIndex = 0;
            for (i = 0; i < Length; i++)
            {
                if (Data[i] > MaxValue)
                {
                    MaxValue = Math.Abs(Data[i]);
                    MaxIndex = i;
                }
            }
            return MaxIndex;
        }
        //计算一维DOUBLE数组均值
        public static double RowMeanVolue__2DDoubleCalculate(double[,] Data, int Row, int Col)
        {
            int i;
            double AddValue = 0;
            for (i = 0; i < Col; i++)
            {
                AddValue = AddValue + Data[Row, i];
            }
            double ReturnValue = AddValue / (double)Col;
            return ReturnValue;
        }
        //计算二维Double数组最大值
        public static double MaxValue_2DDoubleCalculate(double[,] Data, int Row, int Col)
        {
            int i;
            int j;
            double MaxValue = 0;
            for (i = 0; i < Row; i++)
            {
                for (j = 0; j < Col; j++)
                {
                    if (Math.Abs(Data[i, j]) > MaxValue)
                    {
                        MaxValue = Math.Abs(Data[i, j]);
                    }
                }
            }
            return MaxValue;
        }
        //计算二维Double数组最大值所在坐标
        public static Point MaxValueAnddPoint_2DDoubleCalculate(double[,] Data, int Row, int Col)
        {
            int i;
            int j;
            double Temp = 0;
            Point MaxPoint = new Point();
            for (i = 0; i < Row; i++)
            {
                for (j = 0; j < Col; j++)
                {
                    if (Math.Abs(Data[i, j]) > Temp)
                    {
                        Temp = Math.Abs(Data[i, j]);
                        MaxPoint.X = j;
                        MaxPoint.Y = i;

                    }
                }
            }
            return MaxPoint;
        }
        //在图像上增加标志
        public static Bitmap Bitmap_Update(Image MyImage, int Width, int High, int X, int Y, int Mark)
        {
            int i;
            int j;
            Bitmap MyBitmap = new Bitmap(130, 600);
            byte[,] Mark0 = new byte[5, 5] { { 0, 0, 1, 1, 1 },
                                             { 0, 1, 0, 0, 1 },
                                             { 1, 0, 0, 0, 1 },
                                             { 0, 1, 0, 0, 1 },
                                             { 0, 0, 1, 1, 1 }};
            byte[,] Mark1 = new byte[5, 5] { { 0, 0, 1, 1, 1 },
                                             { 0, 1, 1, 0, 1 },
                                             { 1, 0, 1, 0, 1 },
                                             { 0, 1, 1, 0, 1 },
                                             { 0, 0, 1, 1, 1 }};
            byte[,] Mark2 = new byte[5, 5] { { 0, 0, 1, 1, 1 },
                                             { 0, 1, 1, 1, 1 },
                                             { 1, 0, 1, 1, 1 },
                                             { 0, 1, 1, 1, 1 },
                                             { 0, 0, 1, 1, 1 }};
            try
            {
                MyBitmap = new Bitmap(MyImage);
                switch (Mark)
                {
                    case 0:
                        {
                            for (i = 0; i < 5; i++)
                            {
                                for (j = 0; j < 5; j++)
                                {
                                    if (Mark0[i, j] == 1)
                                    {
                                        MyBitmap.SetPixel(X + i, Y + j, Color.Red);
                                    }
                                }
                            }
                            break;
                        }
                    case 1:
                        {
                            for (i = 0; i < 5; i++)
                            {
                                for (j = 0; j < 5; j++)
                                {
                                    if (Mark1[i, j] == 1)
                                    {
                                        MyBitmap.SetPixel(X + i, Y + j, Color.Red);
                                    }
                                }
                            }
                            break;
                        }
                    case 2:
                        {
                            for (i = 0; i < 5; i++)
                            {
                                for (j = 0; j < 5; j++)
                                {
                                    if (Mark2[i, j] == 1)
                                    {
                                        MyBitmap.SetPixel(X + i, Y + j, Color.Red);
                                    }
                                }
                            }
                            break;
                        }
                    default:
                        {
                            break;
                        }

                }
                return MyBitmap;
            }
            catch
            {
                return null;
            }
        }
        //二维数组转换为灰度图像
        public static Bitmap TwoDimensionArrayConvertToBitmap(double[,] TwoDimensionArray, int Height, int Width)
        {
            int i;
            int j;
            //计算最大值
            double TwoDimensionArray_MaxValue = MaxValue_2DDoubleCalculate(TwoDimensionArray, Height, Width);
            //定义一个位图
            Bitmap MyBitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
            BitmapData bmpData = MyBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
            // 获取图像参数
            int stride = bmpData.Stride;                      // 扫描线的宽度
            int offset = stride - Width;                      // 显示宽度与扫描线宽度的间隙
            IntPtr iptr = bmpData.Scan0;                      // 获取bmpData的内存起始位置
            int scanBytes = stride * Height;                  // 用stride宽度，表示这是内存区域的大小
            // 下面把原始的显示大小字节数组转换为内存中实际存放的字节数组
            int posScan = 0;// posReal = 0;                    // 分别设置两个位置指针，指向源数组和目标数组
            byte[] pixelValues = new byte[scanBytes];        //为目标数组分配内存
            for (i = 0; i < Height; i++)
            {
                // 下面的循环节是模拟行扫描
                for (j = 0; j < Width; j++)
                {
                    pixelValues[posScan++] = (byte)((256 * TwoDimensionArray[i, j]) / TwoDimensionArray_MaxValue);
                }
                posScan = posScan + offset;                    //行扫描结束，要将目标位置指针移过那段“间隙”
            }
            // 用Marshal的Copy方法，将刚才得到的内存字节数组复制到BitmapData中
            System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
            MyBitmap.UnlockBits(bmpData);  // 解锁内存区域
            // 下面的代码是为了修改生成位图的索引表，从伪彩修改为灰度
            ColorPalette tempPalette;
            using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                tempPalette = tempBmp.Palette;
            }
            for (i = 0; i < 256; i++)
            {
                tempPalette.Entries[i] = Color.FromArgb(i, i, i);
            }
            MyBitmap.Palette = tempPalette;
            // 算法到此结束，返回结果
            return MyBitmap;
        }
        public static void Text_SingleLine_Storage(string FileName, string SingleLineText)
        {
            FileStream MyFileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
            StreamWriter MyStreamWriter = new StreamWriter(MyFileStream);
            MyStreamWriter.WriteLine(SingleLineText);
            MyStreamWriter.Close();
            MyFileStream.Close();
        }
        public static void Text_MoreLine_Storage(string FileName, string[] MoreLineText, int LineNum)
        {
            int i;
            FileStream MyFileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
            StreamWriter MyStreamWriter = new StreamWriter(MyFileStream);
            for (i = 0; i < LineNum; i++)
            {
                MyStreamWriter.WriteLine(MoreLineText[i]);
            }
            MyStreamWriter.Close();
            MyFileStream.Close();
        }
        //存储缺陷数据
        public static void DefectData_Storage(string FileName, Int32[] Position, double[,] Magnetic, int Row, int Col)
        {
            int i;
            int j;
            string LineText = null;
            FileStream MyFileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
            StreamWriter MyStreamWriter = new StreamWriter(MyFileStream);
            for (i = 0; i < Col; i++)
            {
                LineText = Position[i].ToString() + "," + Magnetic[0, i].ToString() + "," +
                                                       Magnetic[1, i].ToString() + "," +
                                                       Magnetic[2, i].ToString() + "," +
                                                       Magnetic[3, i].ToString() + "," +
                                                       Magnetic[4, i].ToString() + "," +
                                                       Magnetic[5, i].ToString() + "," +
                                                       Magnetic[6, i].ToString() + "," +
                                                       Magnetic[7, i].ToString() + "," +
                                                       Magnetic[8, i].ToString() + "," +
                                                       Magnetic[9, i].ToString();


                MyStreamWriter.WriteLine(LineText);
            }
            MyStreamWriter.Close();
            MyFileStream.Close();
        }
        public static Color UInt16ToColor1(Double Value)
        {
            Color MyColor = new Color();
            UInt16 C = (UInt16)(Value);       //16进制颜色值
            byte R, G, B;   //8位RGB值 
            R = (byte)(C >> 10);              //取出高位R的分量
            G = (byte)((C >> 5) & 0x1f);      //取出高位G的分量
            B = (byte)(C & 0x1f);             //取出高位B的分量 
            MyColor = Color.FromArgb(255, R, G, B);  //这个是16位组合5位R、5位G、5位B 
            return MyColor;
        }
        public static Color UInt16ToColor2(Double Value)
        {
            Color MyColor = new Color();
            if (Value >= 0 && Value < 10000)
            {
                MyColor = Color.White;
            }
            else if (Value >= 10000 && Value < 20000)
            {
                MyColor = Color.Azure;
            }
            else if (Value >= 20000 && Value < 30000)
            {
                MyColor = Color.Yellow;
            }
            else if (Value >= 30000 && Value < 40000)
            {
                MyColor = Color.Gray;
            }
            else if (Value >= 40000 && Value < 50000)
            {
                MyColor = Color.Blue;
            }
            else
            {
                MyColor = Color.Red;
            }
            return MyColor;
        }
        public static Bitmap TwoDArrayToBitmap(double[,] Data, int Row, int Col, double ThreshodValue)
        {
            int i;
            int j;
            Bitmap MyBitmap = new Bitmap(Row, Col);
            double[] RowMeanValue = new double[Row];
            try
            {
                for (i = 0; i < Row; i++)
                {
                    RowMeanValue[i] = RowMeanVolue__2DDoubleCalculate(Data, i, Col);
                    for (j = 0; j < Row; j++)
                    {
                        if (Math.Abs(Data[i, j] - RowMeanValue[i]) >= ThreshodValue)
                        {
                            MyBitmap.SetPixel(i, j, Color.Red);
                        }
                        else
                        {
                            MyBitmap.SetPixel(i, j, Color.Black);
                        }
                    }
                }
                return MyBitmap;
            }
            catch
            {
                return null;
            }
        }
        //16进制转换为RGB彩色
        int MagnetictoRGB(UInt16 MagneticValue)
        {
            int[] RGBValues = new int[3] { 0, 0, 0 };
            byte MagneticGrayValue = (byte)(MagneticValue >> 8);
            if (MagneticGrayValue < 64)
            {
                RGBValues[2] = 0;
                RGBValues[1] = (int)(4 * MagneticGrayValue);
                RGBValues[0] = 255;
            }
            else if (MagneticGrayValue >= 64 && MagneticGrayValue < 128)
            {
                RGBValues[2] = 0;
                RGBValues[1] = 255;
                RGBValues[0] = (int)(2 * 255 - 4 * MagneticGrayValue);
            }
            else if (MagneticGrayValue >= 128 && MagneticGrayValue < 192)
            {
                RGBValues[2] = (int)(4 * MagneticGrayValue - 2 * 255);
                RGBValues[1] = 255;
                RGBValues[0] = 0;
            }
            else
            {
                RGBValues[2] = 255;
                RGBValues[1] = (int)(4 * 255 - 4 * MagneticGrayValue);
                RGBValues[0] = 0;
            }
            return ((RGBValues[2] << 7 & 0x7c00) | (RGBValues[1] << 2 & 0x3e0) | (RGBValues[0] & 0x1f) | 0x8000);
        }

        public static void DrawNumberedCircleTriangle(Bitmap bitmap, int centerX, int centerY, int str)
        {
            string stu;
            if (str == 1)
            {
                stu = "①";
            }
            else if (str == 2)
            {
                stu = "②";
            }
            else
            {
                stu = "▲";
            }
            centerY = Math.Abs(centerY);

            int[] xCoords = new int[3];
            int[] yCoords = new int[3];

            xCoords[0] = centerX;
            yCoords[0] = centerY - (int)(20 * Math.Sqrt(3) / 3);

            xCoords[1] = centerX - (int)(20 / 2);
            yCoords[1] = centerY + (int)(20 * Math.Sqrt(3) / 6);

            xCoords[2] = centerX + (int)(20 / 2);
            yCoords[2] = centerY + (int)(20 * Math.Sqrt(3) / 6);

            // 设置字体相关属性
            Font font = new Font("Arial", 20, FontStyle.Bold);
            Brush brush = new SolidBrush(Color.Red);
            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;

            // 在三角形内合适位置添加带圈数字标识
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                // 计算三角形内圈1的位置（这里简单取中心位置偏上一点）
                int circle1X = centerX;
                int circle1Y = centerY;

                // 绘制圈1标识
                graphics.DrawString(stu, font, brush, circle1X, circle1Y, stringFormat);
            }

            //警报声.告警声音.AlarmSound();
        }
    }

}